package de.tmahr.android;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import de.tmahr.android.logger.LogActivity;

import android.content.Context;
import android.os.Bundle;

public class InternalStorageTest extends LogActivity
{
	public InternalStorageTest()
	{
		super("InternalStorageTest");
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		String fileName = "intern.txt";
		String zuSpeichernderText = "Dies ist ein Test des internen Speichers";
		
		log("Speichere: " + zuSpeichernderText);
		try
		{
			writeTextFile(fileName,zuSpeichernderText);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		try
		{
			log("Lade: " + readTextFile(fileName));
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	private String readTextFile(String fileName) throws IOException
	{
		FileInputStream fis = openFileInput(fileName);
		ByteArrayOutputStream bs = new ByteArrayOutputStream();
		byte[] bytes = new byte[4096];
		int len;
		while((len=fis.read(bytes))>0)
		{
			bs.write(bytes,0,len);
		}
		fis.close();
		return new String(bs.toByteArray(),"UTF8");
	}

	private void writeTextFile(String fileName, String text) throws IOException
	{
		FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
		fos.write(text.getBytes());
		fos.close();		
	}	
}
